const jwt = require("jsonwebtoken");
// 添加热门城市中的景点
const City = require("../models/City");
const Sight = require("../models/Sight");
const Comment = require("../models/Comment");
const Spot = require("../models/Spot");
const User = require("../models/User");
const Favorite = require("../models/Favorite");
const { secret } = require("../config/config");
// 获取热门城市中的某个景点详情
exports.getSpot = async (req, res) => {
  try {
    const { cityId, spotId } = req.params;
    let userId;
    console.log(req.headers.token);
    if (req.headers.token) {
      const user = await jwt.verify(req.headers.token, secret);
      console.log(user, "*&&S&D&S&D&S&D&S&");
      userId = user.id;
    }
    // const spot = await Spot.findById(spotId);
    const spot = await Spot.findOne({
      where: {
        // cityId,
        id: spotId,
      },
      include: [
        // {
        //   model: Comment,
        //   include: {
        //     model: User,
        //     attributes: ["id", "email"],
        //   },
        // },
        {
          model: City,
        },
        {
          model: Sight,
        },
      ],
    });
    const user = await User.findOne({
      where: {
        id: spot.userId,
      },
    });
    console.log(user, "00000000000");
    if (userId) {
      favorite = await Favorite.findOne({
        where: {
          spotId,
          userId,
        },
      });
    } else {
      favorite = false;
    }

    if (!spot) {
      return res.status(404).send("景点不存在");
    }
    const comments = await Comment.findAll({
      where: {
        spotId,
      },
      order: [["createdAt", "DESC"]],
    });
    for (let i = 0; i < comments.length; i++) {
      const user = await User.findOne({
        where: {
          id: comments[i].userId,
        },
      });
      comments[i].userId = user;
      comments[i].save();
    }
    res.json({
      spot,
      isFavorite: favorite ? true : false,
      user,
      comments,
    });
  } catch (error) {
    console.log(error);
    res.status(500).send("服务器错误");
  }
};
exports.addSpot = async (req, res) => {
  try {
    let { cityId } = req.params;
    let { sightId } = req.query;
    const { name, description, image } = req.body;
    if (sightId) {
      const sight = await Sight.findOne({ where: { id: sightId } });
      if (!sight) {
        return res.status(404).send("景色分类不存在不存在");
      }
    } else {
      const city = await City.findOne({ where: { id: cityId } });
      if (!city) {
        return res.status(404).send("城市不存在");
      }
    }

    const spot = await Spot.create({
      name,
      description,
      image,
      cityId: cityId && !sightId ? cityId : null,
      sightId: sightId ? sightId : null,
      userId: req.user.id,
    });
    res.json(spot);
  } catch (error) {
    console.log(error);
    res.status(500).send("服务器错误");
  }
};
// 获取热门景点
exports.getHotSpots = async (req, res) => {
  console.log(req.params.cityId);
  try {
    const id = req.params.cityId;
    if (!id) {
      const spots = await Spot.findAll({
        limit: +req.query?.limit || 3,
        order: [["createdAt", "DESC"]],
      });
      return res.json(spots);
    }
    const spots = await Spot.findAll({
      where: {
        cityId: id,
      },
      order: [["createdAt", "DESC"]],
    });
    res.json(spots);
  } catch (error) {
    console.log(error);
    res.status(500).send("服务器错误");
  }
};
// 获取热门城市中的某个景点评论列表
exports.getSpotComments = async (req, res) => {
  try {
    const { cityId, spotId } = req.params;
    const comments = await Comment.findAll({
      where: {
        cityId,
        spotId,
      },
      order: [["createdAt", "DESC"]],
      include: [
        {
          model: User,
        },
        {
          model: Spot,
        },
      ],
    });
    res.json(comments);
  } catch (error) {
    console.log(error);
    res.status(500).send("服务器错误");
  }
};

// 添加热门城市中的某个景点评论
exports.addSpotComment = async (req, res) => {
  try {
    const { cityId, spotId } = req.params;
    const { text } = req.body;
    const comment = await Comment.create({
      text,
      cityId,
      spotId,
      userId: req.user.id,
    });
    res.json(comment);
  } catch (error) {
    res.status(500).send("服务器错误");
  }
};

exports.addSpotCollection = async (req, res) => {
  const spotId = req.params.spotId;
  const userId = req.user.id;
  try {
    const collect = await Favorite.findOne({ where: { spotId, userId } });
    console.log(collect);
    if (collect) return res.json({ msg: "已经收藏过了" });
    const favorite = await Favorite.create({
      spotId: spotId,
      userId: req.user.id,
    });
    res.json(favorite);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "收藏失败" });
  }
};
exports.delSpotCollection = async (req, res) => {
  const favoriteId = req.params.spotId;
  try {
    await Favorite.destroy({ where: { spotId: favoriteId } });
    res.json({ msg: "删除收藏成功" });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "删除收藏失败" });
  }
};

exports.getCollection = async (req, res) => {
  const userId = req.user.id;
  try {
    const collections = await Favorite.findAll({
      where: {
        userId,
      },
      include: {
        model: Spot,
      },
      order: [["createdAt", "DESC"]],
    });
    res.json(collections);
  } catch (error) {
    res.status(500).json({ error: "获取失败" });
  }
};
